package com.atguigu.spzx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.exception.GuiguException;
import com.atguigu.spzx.exception.spzxGuiguExceptions;
import com.atguigu.spzx.mapper.SysUserMapper;
import com.atguigu.spzx.service.SysUserService;
import com.atguigu.spzx.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.util.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public
    LoginVo login(LoginDto loginDto) {
        String userName = loginDto.getUserName();
        String loginDtoPassword = loginDto.getPassword();
        if (!StringUtils.hasText(userName) || !StringUtils.hasText(loginDtoPassword)){
                throw new spzxGuiguExceptions(ResultCodeEnum.USERNAME_PASSWORD_ERROR);
        }
        SysUser sysUser = sysUserMapper.selectUserNamesssss(userName);
        if (sysUser == null){
            throw new spzxGuiguExceptions(ResultCodeEnum.USERNAME_PASSWORD_ERROR);
        }
        String passwordMD5 = DigestUtils.md5DigestAsHex(loginDtoPassword.getBytes());
        if (!sysUser.getPassword().equals(passwordMD5)){
            throw new spzxGuiguExceptions(ResultCodeEnum.LOGIN_ERROR);
        }
        if (sysUser.getStatus().intValue() != 1){
            throw new spzxGuiguExceptions(ResultCodeEnum.ACCOUT_STOP);
        }
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String Userstring = JSONObject.toJSONString(sysUser);

        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_PREFIX+token,Userstring,RedisConstant.USER_LOGIN_TIMEOUT, TimeUnit.MINUTES);
        LoginVo loginVo =  new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }
}
